package com.littcore.saap.common.session;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.littcore.saap.common.cache.manager.SessionCacheManager;
import com.littcore.saap.common.cache.manager.UserSessionCacheManager;
import com.littcore.saap.common.cache.model.UserSessionVo;
import com.littcore.saap.core.service.ISessionManager;
import com.littcore.saap.core.web.util.RequestUtils;
import com.littcore.shield.vo.ILoginVo;
import com.littcore.web.util.WebUtils;

@Service
public class SessionManager  implements ISessionManager{
    
    @Resource
    private SessionCacheManager sessionCacheManager;
    
    @Resource
    private UserSessionCacheManager userSessionCacheManager;
    
    public void cacheSession(String sessionId,ILoginVo user, HttpServletRequest request){
        if(user==null){
            return;
        }
       
        String loginDevice=RequestUtils.getLoginDevice(request);
        
        String remoteIp=WebUtils.getRemoteIp(request);
        String browser=RequestUtils.getBrowser(request);
        UserSessionVo userSessionVo=new UserSessionVo(sessionId,loginDevice,user.getOpId().intValue(),remoteIp);      
        userSessionVo.setBrowser(browser);
        sessionCacheManager.cacheSession(sessionId, user);
        userSessionCacheManager.cacheUserSession(userSessionVo);
    }
    
    public void updateSession(ILoginVo user,HttpServletRequest request){
        if(user==null){
            return;
        }
       Set<String> sessionIds= userSessionCacheManager.getSessionByUserId(user.getOpId().intValue());
       for(String sessionId:sessionIds){
           sessionCacheManager.cacheSession(sessionId, user);
       }
    }
    
    public void removeSession(HttpServletRequest request){
        String sessionId=request.getRequestedSessionId();
        String loginDevice=RequestUtils.getLoginDevice(request);
        
        String remoteIp=WebUtils.getRemoteIp(request);

          
        ILoginVo  user=sessionCacheManager.getSession(sessionId);
        if(user!=null){
            sessionCacheManager.removeSession(sessionId); 
            UserSessionVo userSessionVo=new UserSessionVo(sessionId,loginDevice,user.getOpId().intValue(),remoteIp);  
            userSessionCacheManager.removeUserSession(userSessionVo);
        }
        
        
       
    }
    
    public boolean isContain(String sessionId){
        return sessionCacheManager.isContain(sessionId);
    }
    
    public ILoginVo getSession(String sessionId){
        return sessionCacheManager.getSession(sessionId);
    }

}
